/*
 * Copyright 2017, OpenRemote Inc.
 *
 * See the CONTRIBUTORS.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.openremote.agent.protocol.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.openremote.agent.protocol.io.AbstractNettyIOServer;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Abstract IO Server for creating TCP socket servers that clients can connect to. Concrete implementation need
 * to configure the pipeline with the necessary encoders and decoders to ensure messages of type &lt;T&gt; are
 * generated/consumed at/from the end/start of the pipeline.
 */
public abstract class AbstractTCPServer<T> extends AbstractNettyIOServer<T, SocketChannel, ServerBootstrap, InetSocketAddress> {

    protected SocketAddress localAddress;

    public AbstractTCPServer(InetSocketAddress localAddress) {
        this.localAddress = localAddress;
    }

    @Override
    protected String getSocketAddressString() {
        return localAddress == null ? null : "tcp://" + localAddress;
    }

    @Override
    protected ServerBootstrap createAndConfigureBootstrap() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.group(workerGroup);
        bootstrap.localAddress(localAddress);
        bootstrap.option(ChannelOption.SO_BACKLOG, clientLimit);

        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) {
                AbstractTCPServer.this.initClientChannel(channel);
            }
        });

        return bootstrap;
    }

    @Override
    protected String getClientDescriptor(SocketChannel client) {
        return client == null || client.remoteAddress() == null ? null : "tcp://" + client.remoteAddress();
    }
}
